<?php

namespace App\HttpController\Admin;

use App\HttpController\BaseController;
use App\Model\AdminsModel;
use App\Utility\Captcha;
use App\Utility\Token;
use Carbon\Carbon;


class Login extends BaseController {

    public function index(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            //验证验证码
            $check = (new Captcha())->check($data['captcha'],$data['captchaKey']);
            if($check === false){
                return $this->writeJson(1,'','验证码错误');
            }
            //判断用户非法
            $model = new AdminsModel();
            $user = $model->check($data);
            if($user !== false){
                //更新登陆信息
                $update = ['id' => $user['id'], 'login_at' => Carbon::now()];
                $model->update($update);
                $token = Token::sessionEncrypt($data['username']);
                return $this->writeJson(0,$token,'登录成功，页面即将跳转...');
            }
            return $this->writeJson(1,'','用户名或者密码输入错误');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


    public function captcha(){
        $captcha = (new Captcha())->create();
        return $this->writeJson(200,$captcha,'SECCUSS');
    }
}

